package com.zheng.wechat.mp.admin.controller.manage;

import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.JsonUtil;
import com.zheng.common.util.PropertiesUtil;
import com.zheng.wechat.mp.common.constant.WechatMpConstant;
import com.zheng.wechat.mp.common.constant.WechatMpResult;
import com.zheng.wechat.mp.common.constant.WechatMpResultConstant;
import com.zheng.wechat.mp.dao.model.*;
import com.zheng.wechat.mp.rpc.api.WechatMpArticleImageService;
import com.zheng.wechat.mp.rpc.api.WechatMpArticleService;
import com.zheng.wechat.mp.rpc.api.WechatMpWebJwidService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2018/11/8.
 */
@Controller
@RequestMapping("/manage/article")
@Api(value = "文章控制器", description = "文章控制器")
public class ArticleController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CategoryController.class);

    @Autowired
    private WechatMpArticleService wechatMpArticleService;

    @Autowired
    private WechatMpArticleImageService wechatMpArticleImageService;
    @Autowired
    private WechatMpWebJwidService wechatMpWebJwidService;
    /**
     * 文章首页
     * @return
     */
    @ApiOperation(value = "文章首页")
    @RequiresPermissions("wechatmp:article:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index() {
        return "/manage/article/index.jsp";
    }

    @ApiOperation(value = "文章图标管理页面")
    @RequiresPermissions("wechatmp:article:imageManage")
    @RequestMapping(value = "/iamgeManage/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    public String iamgeManage(@PathVariable("id") int id, ModelMap modelMap) {
        modelMap.put("articleId",id);
        WechatMpArticleImageExample example = new WechatMpArticleImageExample();
        WechatMpArticleImageExample.Criteria criteria = example.createCriteria();
        criteria.andArticleIdEqualTo(id);
        List<WechatMpArticleImage> images = wechatMpArticleImageService.selectByExample(example);
        JSONArray array = new JSONArray();
        for(WechatMpArticleImage image : images){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key",image.getId());
            jsonObject.put("width","120px");
            jsonObject.put("caption",image.getImage());
            jsonObject.put("url","/manage/article/deleteImage/"+image.getId());
            array.add(jsonObject);
        }
        modelMap.put("images", JsonUtil.object2Json(array));
        return "/manage/article/imageManage.jsp";
    }

    @ApiOperation(value = "获取图片")
    @RequiresPermissions("wechatmp:article:imageManage")
    @RequestMapping(value = "/loadImage/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void loadImage(@PathVariable("id") int id,
                          HttpServletRequest request, HttpServletResponse response) throws IOException {
        WechatMpArticleImage image = wechatMpArticleImageService.selectByPrimaryKey(id);
        if(image != null){
            FileInputStream ips = null;
            OutputStream out = null;
            try {
                //获取图片存放路径
                File file = new File(image.getPath() +"/" + image.getImage());
                String prefix = image.getImage().substring(image.getImage().lastIndexOf("."));
                ips = new FileInputStream(file);
                out = response.getOutputStream();
                response.setContentType("image/"+prefix);
                //读取文件流
                int len = 0;
                byte[] buffer = new byte[1024 * 10];
                while ((len = ips.read(buffer)) != -1){
                    out.write(buffer,0,len);
                }
                out.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                out.close();
                ips.close();
            }
        }
    }

    @ApiOperation(value = "删除图片")
    @RequiresPermissions("wechatmp:article:imageManage")
    @RequestMapping(value = "/deleteImage/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object deleteImage(@PathVariable("id") int id) {
        wechatMpArticleImageService.deleteByPrimaryKey(id);
        return new WechatMpResult(WechatMpResultConstant.SUCCESS,null);
    }

    @ApiOperation(value = "上传图片")
    @RequiresPermissions("wechatmp:article:imageManage")
    @RequestMapping(value = "/upload/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONObject upload(@PathVariable("id") int id,@RequestParam(value = "file_data") MultipartFile file) throws IOException {
        String path = PropertiesUtil.getInstance().getValue(WechatMpConstant.UPLOAD_FILE_PATH) + "article";
        File f = new File(path);
        if (!f.exists())
            f.mkdirs();
        String name = file.getOriginalFilename();
        String prefix = name.substring(name.lastIndexOf("."));
        String fileName = UUID.randomUUID() + prefix;
        f = new File(path + "/" + fileName);
        if (!f.exists()) {
            f.createNewFile();
            file.transferTo(f);
        }
        WechatMpArticleImage image = new WechatMpArticleImage();
        image.setArticleId(id);
        image.setImage(fileName);
        image.setOrders(System.currentTimeMillis());
        image.setPath(path);
        int imageId = wechatMpArticleImageService.insertSelective(image,"id");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key",imageId);
        jsonObject.put("width","120px");
        jsonObject.put("caption",image.getImage());
        jsonObject.put("url","/manage/article/deleteImage/"+imageId);
        return jsonObject;
    }

    @ApiOperation(value = "目录接口")
    @RequiresPermissions("wechatmp:article:read")
    @RequestMapping(value = "/category", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object category(@RequestParam(required = false, value = "id") Integer id) {
        WechatMpCategoryExample example = new WechatMpCategoryExample();
        WechatMpCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        if(id != null)
            criteria.andPidEqualTo(id);
        else
            criteria.andPidIsNull();
        JSONArray array = new JSONArray();
        List<WechatMpCategory> categoryList = wechatMpArticleService.getCategoryList(example);
        for(WechatMpCategory category : categoryList){
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("id",category.getId());
            jsonObject.put("pid",category.getPid());
            jsonObject.put("name",category.getName());
            jsonObject.put("isParent",id==null ? "true":"false");
            jsonObject.put("open","false");
            array.add(jsonObject);
        }
        return array;
    }



    @ApiOperation(value = "文章列表")
    @RequiresPermissions("wechatmp:article:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
            @RequestParam(required = false, value = "categoryId") Integer categoryId,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        WechatMpArticleExample wechatMpArticleExample = new WechatMpArticleExample();
        WechatMpArticleExample.Criteria criteria = wechatMpArticleExample.createCriteria();
        criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            wechatMpArticleExample.setOrderByClause(sort + " " + order);
        }else{
            wechatMpArticleExample.setOrderByClause("orders asc");
        }
        if(categoryId!=null){
            criteria.andCategoryIdEqualTo(categoryId);
        }
        if (StringUtils.isNotBlank(search)) {
            wechatMpArticleExample.or()
                    .andTitleLike("%" + search + "%");
        }
        List<WechatMpArticle> rows = wechatMpArticleService.selectByExample(wechatMpArticleExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        return result;
    }

    @ApiOperation(value = "新增文章")
    @RequiresPermissions("wechatmp:article:create")
    @RequestMapping(value = "/create/{id}", method = {RequestMethod.GET})
    public String create(@PathVariable("id") int id, ModelMap modelMap) {
        WechatMpWebJwidExample wechatMpWebJwidExample = new WechatMpWebJwidExample();
        wechatMpWebJwidExample.setOrderByClause("id asc");
        List<WechatMpWebJwid> wechatMpWebJwidList = wechatMpWebJwidService.selectByExample(wechatMpWebJwidExample);
        modelMap.put("wechatMpWebJwidList", wechatMpWebJwidList);

        modelMap.put("categoryId", id);
        return "/manage/article/create.jsp";
    }



    @ApiOperation(value = "新增文章")
    @RequiresPermissions("wechatmp:article:create")
    @ResponseBody
    @RequestMapping(value = "/create/{categoryId}", method = {RequestMethod.POST})
    public Object create(@PathVariable("categoryId") int categoryId,WechatMpArticle wechatMpArticle ) {
        long time = System.currentTimeMillis();
        wechatMpArticle.setCategoryId(categoryId);
        wechatMpArticle.setCtime(time);
        wechatMpArticle.setCuser(getLoginUserName());
        if(wechatMpArticle.getOrders() == null){
            wechatMpArticle.setOrders(time);
        }
        int count = wechatMpArticleService.insertSelective(wechatMpArticle);
        return new WechatMpResult(WechatMpResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "删除文章")
    @RequiresPermissions("wechatmp:article:delete")
    @RequestMapping(value = "/delete/{ids}",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        int count = wechatMpArticleService.deleteByPrimaryKeys(ids);
        return new WechatMpResult(WechatMpResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改文章")
    @RequiresPermissions("wechatmp:article:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.GET})
    public String update(@PathVariable("id") int id, ModelMap modelMap) {
        WechatMpWebJwidExample wechatMpWebJwidExample = new WechatMpWebJwidExample();
        wechatMpWebJwidExample.setOrderByClause("id asc");
        List<WechatMpWebJwid> wechatMpWebJwidList = wechatMpWebJwidService.selectByExample(wechatMpWebJwidExample);
        modelMap.put("wechatMpWebJwidList", wechatMpWebJwidList);
        WechatMpArticle wechatMpArticle  = wechatMpArticleService.selectByPrimaryKey(id);
        modelMap.put("wechatMpArticle", wechatMpArticle);
        return "/manage/article/update.jsp";
    }

    @ApiOperation(value = "修改文章")
    @RequiresPermissions("wechatmp:article:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public Object update(@PathVariable("id") int id, WechatMpArticle wechatMpArticle ) {
        wechatMpArticle.setId(id);
        int count = wechatMpArticleService.updateByPrimaryKeySelective(wechatMpArticle);
        return new WechatMpResult(WechatMpResultConstant.SUCCESS, count);
    }

}
